package com.aidex.web.controller.api;

import com.aidex.biz.domain.*;
import com.aidex.biz.service.*;
import com.aidex.common.config.AiDexConfig;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.entity.Company;
import com.aidex.common.core.page.PageDomain;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.uuid.UUID;
import com.aidex.system.service.CompanyService;
import com.aidex.system.service.SysNoticeService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lop.open.api.sdk.LopException;
import com.lop.open.api.sdk.response.ECAP.EcapV1OrdersCreateLopResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;

/**
 * 小程序业务员接口
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2022-09-21
 */
@RestController("ApiVisitUserInfoController")
@RequestMapping("/api/visitUserInfo")
@Component
public class VisitUserInfoController extends BaseController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private EquInfoService equInfoService;
    @Autowired
    private RubbishTypeService rubbishTypeService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private AppointmentService appointmentService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private WeChatLoginService weChatLoginService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailsService orderDetailsService;

    @Autowired
    private SysNoticeService sysNoticeService;

    @Autowired
    private OrderImageService orderImageService;

    @Autowired
    private BillInfoDetailsService billInfoDetailsService;
    @Autowired
    private BillInfoService billInfoService;
    @Autowired
    private JdKuaiyunService jdKuaiyunService;

    @Autowired
    private JdkyOrderService jdkyOrderService;

    @Autowired
    private QingYangOrderService qingYangOrderService;

    @Autowired
    private UserTixianService userTixianService;

    @Autowired
    private RefundOrderService refundOrderService;



    /**
     * 更新订单详情信息
     *
     * @param orderDetails
     * @return
     */
    @PostMapping("/updateOrderDetailsQrCode")
    public R orderDetailsQrCode(@RequestBody OrderDetails orderDetails) {
        return R.status(orderDetailsService.save(orderDetails));
    }

    /**
     * 查询用户订单列表
     *
     * @return
     * @ companyId 公司ID
     * @ status 状态 洗护订单
     * @ orderType 订单类型 0 洗护订单 1 商城订单
     * -1待支付
     * 0已支付，待入柜
     * 1已入柜，待取走
     * 2已取衣，送洗中
     * 3已分拣 ，洗涤中
     * 4已精洗 ，待分装
     * 5已收纳，待配送
     * 6 已到店，待取货
     * 7已完成
     * 9售后单
     * -99 取消订单
     * 商城订单 -1待支付 0 已支付，待取货  1已完成 9售后单 -99 取消订单
     * @
     */
    @GetMapping("/getShopUserOrderInfoList")
    public R<PageInfo<Order>> getShopUserOrderInfoList(Order order, HttpServletRequest request,
            HttpServletResponse response) {
        order.setPage(new PageDomain(request, response));
        order.getPage().setIsAsc(order.getOrder());
        return R.data(orderService.findPageSelf(order));
    }


    /**
     * 转订单
     *
     * @return
     */
    @GetMapping("/shareOrderTo")
    public R shareOrderTo(@RequestParam String orderId) throws Exception {
        Order order = new Order();
        order.setId(orderId);
        // 平台ID
        order.setCompanyId(AiDexConfig.getCompanyId());
        order.setStatus("1");
        // 发送京东快递
        EcapV1OrdersCreateLopResponse ecapV1OrdersCreateLopResponse=
                jdKuaiyunService.sendJdKuaiYuanOrder(order);
        JdkyOrder jdkyOrder=new JdkyOrder();
        jdkyOrder.setOrderId(order.getId());
        if("0".equals(ecapV1OrdersCreateLopResponse.getCode())){
            order.setDeliveryNo(ecapV1OrdersCreateLopResponse.getResult().getData().getWaybillCode());
            jdkyOrder.setOrderCode(ecapV1OrdersCreateLopResponse.getResult().getData().getWaybillCode());
            jdkyOrder.setStatus("1");
            jdkyOrder.setSenderName(order.getLianxiName());
            jdkyOrder.setSenderPhone(order.getPhone());
            jdkyOrder.setSenderAddress(order.getRoomAddress());
            jdkyOrder.setType("0");
            jdkyOrder.setCompanyId(order.getCompanyId());
            // 修改轻氧运单号
            JSONObject jsonObject=qingYangOrderService.modifyDeliveryNumber(order);
            if("200".equals(jsonObject.getString("code"))){
                jdkyOrder.setStatus("2");
                jdkyOrder.setRemark("京东快运订单推送成功！");
            }else{
                jdkyOrder.setRemark(jsonObject.toString());
            }
            jdkyOrderService.save(jdkyOrder);
        }
        return R.status(orderService.save(order));
    }


    /**
     * 订单衣服照片
     *
     * @param orderImage
     * @return
     */
    @PostMapping("/uploadClothsImage")
    public R uploadClothsImages(@RequestBody OrderImage orderImage) {
        orderImage.setId(UUID.randomUUID().toString());
        orderImage.setIsNewRecord();
        if(orderImageService.save(orderImage)){
            return R.data(orderImage.getId());
        }else{
            return R.status(false);
        }

    }


    /**
     * 删除衣服照片
     *
     * @param orderImage
     * @return
     */
    @PostMapping("/deleteOrderImageByIds")
    public R deleteOrderImageByIds(@RequestBody OrderImage orderImage) {
        return R.status(orderImageService.deleteOrderImageByIds(new String[]{orderImage.getId()}));
    }


    /**
     * 订单商城订单完成
     */
    @PostMapping("/orderSuccess")
    public R orderSuccess(@RequestBody Order order) {
        Order oldOrder = orderService.get(order.getId());
        if (!"2".equals(oldOrder.getStatus())) {
            order.setStatus("2");// 订单完成
            orderService.save(order);
            // 获取积分 TODO
            // 更新销售数量
            orderService.updateOutCount(order);
        }
        return R.success();
    }


    /**
     * 洗护订单揽件完成 打印订单小票
     */
    @PostMapping("/orderQuJian")
    public R orderQuJian(@RequestBody Order order) {
        // order.setStatus("1");
        if(order.getStatus().equals("-88")){
            // 商家取消订单
            order = orderService.get(order.getId());
            order.setStatus("-88");
            // 退款订单
            RefundOrder refundOrder = new RefundOrder();
            refundOrder.setOrderId(order.getId());
            refundOrder.setStatus("0");// 待处理
            refundOrder.setRefundMoeny(order.getPayAmount());
            refundOrder.setOrderType(order.getOrderType());
            refundOrder.setId(order.getId());
            refundOrder.setIsNewRecord();
            refundOrder.setUserInfoId(order.getUserInfoId());
            refundOrder.setRemark("商家拒绝接单");
            refundOrderService.save(refundOrder);
        }
        return R.status(orderService.save(order));
    }

    /**
     * 洗护订单完成
     */
    @PostMapping("/orderSuccessByXiHu")
    public R orderSuccessByXiHu(@RequestBody Order order) {
        Order oldOrder = orderService.get(order.getId());
        if (!"2".equals(oldOrder.getStatus())) {
            order.setStatus("2");// 订单完成
            orderService.save(order);
            // 获取积分 TODO
            // 更新销售数量
            orderService.updateOutCount(order);

        }
        return R.success();
    }

    /**
     * 日报表
     * @return
     */
    @PostMapping("/getShopDay")
    public R getShopDay(@RequestBody BillInfoDetails billInfoDetails) {
        return R.data(billInfoDetailsService.findDay(billInfoDetails));
    }



    @GetMapping("/billDetailsList")
    public R<PageInfo> list(BillInfoDetails billInfoDetails, HttpServletRequest request, HttpServletResponse response)
    {

        billInfoDetails.setPage(new PageDomain(request, response));
        return R.data(billInfoDetailsService.findPage(billInfoDetails));
    }

    /**
     * 查询对账信息列表
     */
    @GetMapping("/billInfoList")
    public R<PageInfo> list(BillInfo billInfo, HttpServletRequest request, HttpServletResponse response)
    {
        billInfo.setPage(new PageDomain(request, response));
        return R.data(billInfoService.findPage(billInfo));
    }


    /**
     * 驿站呼叫京东
     *
     * @return
     */
    @GetMapping("/yizhanJDKY")
    public R yizhanJDKY(@RequestParam String companyId) throws LopException, ParseException {
        String orderId = StringUtils.Getnum();
        Company company = companyService.get(companyId);
        EcapV1OrdersCreateLopResponse ecapV1OrdersCreateLopResponse = jdKuaiyunService.companySendJdKuaiYuan(company, orderId);
        if ("0".equals(ecapV1OrdersCreateLopResponse.getCode())) {
            JdkyOrder jdkyOrder = new JdkyOrder();
            jdkyOrder.setOrderId(orderId);
            jdkyOrder.setOrderCode(ecapV1OrdersCreateLopResponse.getResult().getData().getWaybillCode());
            jdkyOrder.setStatus("1");
            jdkyOrder.setSenderName(company.getLianxiUser());
            jdkyOrder.setSenderPhone(company.getLianxiPhone());
            jdkyOrder.setSenderAddress(company.getLianxiAddress());
            jdkyOrder.setType("1");
            jdkyOrder.setCompanyId(companyId);
            return R.status(jdkyOrderService.save(jdkyOrder));
        }else{
            return R.fail("京东下单失败.....");
        }
    }


    /**
     * 查询京东订单推送列表
     */
    @GetMapping("/getJdOrderlist")
    public R<PageInfo> getJdOrderlist(JdkyOrder jdkyOrder, HttpServletRequest request, HttpServletResponse response)
    {
        jdkyOrder.setPage(new PageDomain(request, response));
        return R.data(jdkyOrderService.findPage(jdkyOrder));
    }


    /**
     * 商家提现
     *
     * @param billInfo
     * @return
     */
    @PostMapping("/shopTixian")
    public R shopTixian(@RequestBody BillInfo billInfo) {
        // 查询提现金额
        BillInfo billInfo1 = billInfoService.get(billInfo.getId());
        if(null==billInfo1){
            return R.fail("提现错误！ID ERROR");
        }
        UserInfo userInfo=userInfoService.get(billInfo.getUserInfoId());
        if(null==userInfo){
            return R.fail("提现错误！OPENID ERROR");
        }
        if(!billInfo1.getCompanyId().equals(billInfo.getCompanyId())){
            return R.fail("提现错误！COMPANYID ERROR");
        }
        if(!"0".equals(billInfo1.getStatus())){
            return R.fail("提现错误！状态错误");
        }
        billInfo1.setStatus("1");
        if(billInfoService.save(billInfo1)){
            if (billInfo1.getMoney().compareTo(BigDecimal.ZERO) > 0) {
                UserTixian userTixian=new UserTixian();
                userTixian.setUserInfoId(billInfo.getUserInfoId());
                userTixian.setMoney(billInfo1.getMoney());
                userTixian.setCompanyId(billInfo.getCompanyId());
                userTixian.setId(StringUtils.Getnum());
                userTixian.setIsNewRecord();
                userTixian.setStatus("0");
                userTixian.setBillId(billInfo1.getId());
                userTixianService.save(userTixian);
                return R.success("申请提现成功！1-20分钟到账微信零钱，请注意查收！");
            } else {
                return R.fail("提现金额必须大于零！");
            }
        }else{
            return R.fail("提现失败");
        }
    }
}
